package zdc.ui {
import app.AppConfig;

import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.media.StageVideo;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLRequest;
import flash.utils.Timer;

import org.tuio.TuioTouchEvent;

import zdc.ui.MovingInertia;
import zdc.Util;

/**
 *
 * @author Metal Slime
 */
public class WanderLoader extends MovieClip {
    protected var _v1:MovieClip;
    protected var _v2:MovieClip;
    //缓存图
    protected var _snapShot:DisplayObject;
    //背景
    protected var _bgDio:DisplayObject;
    //手势指示
    protected var _gestureDio:DisplayObject;
    protected var _gestureX:Number = 0;
    protected var _gestureY:Number = 0;

    private var _loader1:Loader;
    private var _loader2:Loader;
    private var _loadedNum:int = 0;
    private var _hasStarted:Boolean = false;
    protected var _src1:String;
    protected var _src2:String;
    protected var _miInited:Boolean = false;

    private var _mi:MovingInertia;
    private var _played1:Boolean = false;
    private var _played2:Boolean = false;
    private var _total:int = 0;

    private var _moving:Boolean = false;
    protected var _recur:Boolean = false;

    private var _timer:Timer;
    private var _checkTime:Number = 1000;

    private var _actZone:Sprite;
    protected var _actZoneWid:Number;
    protected var _actZoneHei:Number;
    protected var _zoneMaxX:Number = 0;
    protected var _zoneMinX:Number = 0;
    protected var _zoneMaxY:Number = 0;
    protected var _zoneMinY:Number = 0;

    protected var _isRemote:Boolean = false;

    protected var _notifying:Boolean = false;
    public static const WANDER_LOADER_CHANGE:String = "WANDER_LOADER_CHANGE";
    public static const WANDER_LOADER_COMPLETE:String = "WANDER_LOADER_COMPLETE";
    public static const WANDER_MI_COMPLETE:String = "WANDER_MI_COMPLETE";
    public static const WANDER_MI_UP:String = "WANDER_MI_UP";

    protected var _walk_type:Boolean = false;
    protected var _distX:Number = 5;
    protected var _distY:Number = 5;

    public function WanderLoader(actWid:Number = 1, actHei:Number = 1) {
        _actZoneWid = actWid;
        _actZoneHei = actHei;

        _bgDio && addChild(_bgDio);
        _snapShot && addChild(_snapShot);
        _loader1 = new Loader();
        _loader2 = new Loader();			//trace(src1, src2, _loadedNum);
        addChild(_loader2);
        addChild(_loader1);
        _loader1.visible = _loader2.visible = false;
        stage ? init() : addEventListener(Event.ADDED_TO_STAGE, init);
    }

    /**
     * 开始加载户型
     */
    public function startLoad():void {
        if (!_hasStarted) {
            _loader1.load(new URLRequest(_src1));
            _hasStarted = true;
        }
    }


    /**
     * 创建动作区域
     */
    private function createActZone():void {				//trace("_actZone", _actZoneWid, _actZoneHei);
        if (_actZone) {
            return;
        }

        _actZone = new Sprite();
        var g:Graphics = _actZone.graphics;
        g.beginFill(0);
        var sw:Number = stage.stageWidth;
        var sh:Number = stage.stageHeight;
        g.beginFill(0, 0);
        g.drawRect(0, 0, sw * _actZoneWid, sh * _actZoneHei);
        g.endFill();
        //addChild(_actZone);
    }

    /**
     * 居中并置顶
     */
    private function centerAndTopActZone():void {
        _actZone.x = this.width - _actZone.width >> 1;
        _actZone.y = this.height - _actZone.height >> 1;
        Util.top(_actZone);
    }

    private function init(e:Event = null):void {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        initVars();
        initState();
        initEvents();
        run();
    }

    private function initVars():void {
    }

    private function onUp(...rest):void {
        _v2.stop();
        _v1.stop();
        if (_played2) {
            _v1.gotoAndStop(_total - _v2.currentFrame);
        }
        if (_played1) {
            _v2.gotoAndStop(_total - _v1.currentFrame);
        }
        dispatchEvent(new WanderLoaderEvent(WANDER_MI_UP));
    }

    private function onMove(e:Object, dx:Number, dy:Number):void {
        if (e.stageX < _zoneMinX || e.stageX > _zoneMaxX) {
            return;
        }
        if (e.stageY < _zoneMinY || e.stageY > _zoneMaxY) {
            return;
        }

        _moving = true;
        if (dx > 0) {
            playV1();
        }
        else if (dx < 0) {
            playV2();
        }
    }

    public function playV1():void {
        _v2.stop();
        if (_played2) {				//trace("_played1");
            _v1.gotoAndStop(_total - _v2.currentFrame);
            _v2.stop();
            _played2 = false;
        }
        _v2.visible = false;
        _v1.visible = true;
        if (!_recur && _v1.currentFrame == _v1.totalFrames) {
            _v1.stop();
        }
        else {
            if (_isRemote) {
                _v1.play();			//trace("_v1.play();");
            } else {
                _v1.currentFrame == _v1.totalFrames ? _v1.gotoAndStop(1) : _v1.nextFrame();
            }
        }
        _played1 = true;

        notify(1);
    }

    private function notify(data:Object = null):void {
        if (_notifying) {
            dispatchEvent(new WanderLoaderEvent(WANDER_LOADER_CHANGE, data));
        }
    }

    public function playV2():void {
        _v1.stop();
        //如果不是可以循环且v1在第一帧
        if (!_recur && _v1.currentFrame == 1) {
            _v2.stop();
            return;
        }
        if (_played1) {					//trace("_played2");
            _v2.gotoAndStop(_total - _v1.currentFrame);
            _v1.stop();
            _played1 = false;
        }
        _v2.visible = true;
        _v1.visible = false;
        if (!_recur && _v2.currentFrame == _v2.totalFrames) {
            _v2.stop();
        }
        else {
            if (_isRemote) {
                _v2.play();
            } else {
                _v2.currentFrame == _v2.totalFrames ? _v2.gotoAndStop(1) : _v2.nextFrame();
            }
        }
        _played2 = true;

        notify(2);
    }

    private function initState():void {
        createActZone();
    }

    private function initEvents():void {
        _loader1.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoReady);
        _loader2.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoReady);

        addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
        addEventListener(Event.EXIT_FRAME, onExitFrame);
    }

    /**
     * 视频加载完毕
     * @param    e
     */
    private function onVideoReady(e:Event):void {
        _loadedNum++;
        e.currentTarget.removeEventListener(Event.COMPLETE, onVideoReady);

        //两个视频加载完毕
        if (_loadedNum >= 2) {
            startMove();
            dispatchEvent(new Event(WANDER_LOADER_COMPLETE));
        }
        else if (_loadedNum == 1) {
            _loader2.load(new URLRequest(_src2));
        }
    }

    private function startMove():void {
        _snapShot && Util.rmChild(_snapShot);
        if (_gestureDio) {
            _gestureDio.x = _gestureX;
            _gestureDio.y = _gestureY;
            //_gestureDio.alpha = 0.5;
            addChild(_gestureDio);
            Util.top(_gestureDio);

        }
        _v1 = _loader1.content as MovieClip;
        _v2 = _loader2.content as MovieClip;

        _loader1.x = _loader2.x = (stage.stageWidth || AppConfig.WID) - _loader1.width >> 1;
        _total = _v1.totalFrames;
        _v1.gotoAndStop(1);
        _v2.gotoAndStop(1);
        _v2.visible = false;
        _loader2.visible = _loader1.visible = _v1.visible = true;

        //计算点击范围
        var sw:Number = stage.stageWidth;
        var sh:Number = stage.stageHeight;
        _zoneMaxX = _zoneMaxX || (sw - ((sw - sw * _actZoneWid) >> 1));
        _zoneMinX = _zoneMinX || ((sw - sw * _actZoneWid) >> 1);
        _zoneMaxY = _zoneMaxY || (sh - ((sh - sh * _actZoneHei) >> 1));
        _zoneMinY = _zoneMinY || ((sh - sh * _actZoneHei) >> 1);

        //addEventListener(Event.ENTER_FRAME, onEnter);
        initMi();
        //centerAndTopActZone();
    }

    /**
     * 初始化动作
     */
    private function initMi():void {
        if (!_miInited && stage) {
            //_mi = new MovingInertia(_actZone, _actZone, TuioTouchEvent.TOUCH_DOWN, TuioTouchEvent.TOUCH_UP, TuioTouchEvent.TOUCH_MOVE, TuioTouchEvent.ROLL_OUT);
            _mi = new MovingInertia(this, this, TuioTouchEvent.TOUCH_DOWN, TuioTouchEvent.TOUCH_UP, TuioTouchEvent.TOUCH_MOVE, TuioTouchEvent.ROLL_OUT);
            if (_walk_type) {
                _mi.WALK_TYPE = _walk_type;
                _mi.addWalkHook(onMove);
                _mi.minWalkDistX = _distX;
            }
            else {
                _mi.addMoveHook(onMove);
            }
            _mi.addUpHook(onUp);
            _mi.enable = true;
            _miInited = true;

            dispatchEvent(new WanderLoaderEvent(WANDER_MI_COMPLETE));
        }
    }

    public function reset():void {
        if (_v1) {
            _v1.stop();
            _v1.visible = true;
        }
        if (_v2) {
            _v2.stop();
            _v2.visible = false;
        }
        _moving = false;
        //trace(_v1, ",", _v2, "reset");
    }

    private function onRemoved(e:Event):void {
        removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
        removeEventListener(Event.ENTER_FRAME, onEnter);
        removeEventListener(Event.EXIT_FRAME, onExitFrame);
        _v1 = _v2 = null;
        _loader1.unloadAndStop();
        _loader2.unloadAndStop();
        _mi = null;

    }

    private function onExitFrame(e:Event):void {
        removeEventListener(Event.EXIT_FRAME, onExitFrame);
    }

    protected function onEnter(e:Event = null):void {
        if (!_moving) {
            _v1.stop();
            _v2.stop();
        }
        if (!_recur && _v1.totalFrames == _v1.currentFrame) {
            _v1.stop();
        }
        if (!_recur && _v2.totalFrames == _v2.currentFrame) {
            _v2.stop();
        }
        _moving = false;
    }

    private function run():void {
        //Helper.initTuio(this);
    }

    [Inspectable(defaultValue='false')]
    public function get recur():Boolean {
        return _recur;
    }

    public function set recur(value:Boolean):void {
        _recur = value;
    }

    public function get src1():String {
        return _src1;
    }

    public function set src1(value:String):void {
        _src1 = value;
    }

    public function get src2():String {
        return _src2;
    }

    public function set src2(value:String):void {
        _src2 = value;
    }

    public function get gestureX():Number {
        return _gestureX;
    }

    public function set gestureX(value:Number):void {
        _gestureX = value;
        if (_gestureDio) {
            _gestureDio.x = _gestureX;
        }
    }

    public function get gestureY():Number {
        return _gestureY;
    }

    public function set gestureY(value:Number):void {
        _gestureY = value;
        if (_gestureDio) {
            _gestureDio.y = _gestureY;
        }
    }

    public function get isRemote():Boolean {
        return _isRemote;
    }

    public function set isRemote(value:Boolean):void {
        _isRemote = value;
    }

    public function get notifying():Boolean {
        return _notifying;
    }

    public function set notifying(value:Boolean):void {
        _notifying = value;
    }

    public function get v1():MovieClip {
        return _v1;
    }

    public function get v2():MovieClip {
        return _v2;
    }

    public function get mi():MovingInertia {
        return _mi;
    }

    public function get zoneMaxX():Number {
        return _zoneMaxX;
    }

    public function set zoneMaxX(value:Number):void {
        _zoneMaxX = value;
    }

    public function get zoneMinX():Number {
        return _zoneMinX;
    }

    public function set zoneMinX(value:Number):void {
        _zoneMinX = value;
    }

    public function get zoneMaxY():Number {
        return _zoneMaxY;
    }

    public function set zoneMaxY(value:Number):void {
        _zoneMaxY = value;
    }

    public function get zoneMinY():Number {
        return _zoneMinY;
    }

    public function set zoneMinY(value:Number):void {
        _zoneMinY = value;
    }

    public function get gestureDio():DisplayObject {
        return _gestureDio;
    }

    //public function get actZoneWid():Number
    //{
    //return _actZoneWid;
    //}
    //
    //public function set actZoneWid(value:Number):void
    //{
    //_actZoneWid = value;
    //}
    //
    //public function get actZoneHei():Number
    //{
    //return _actZoneHei;
    //}
    //
    //public function set actZoneHei(value:Number):void
    //{
    //_actZoneHei = value;
    //}

}

}